# -*- coding:utf-8 -*-
# @Time : 2021/3/6 6:40 下午
# @Author : hyli
# @File : basePage.py
# @Software : PyCharm

import yaml
from appium.webdriver.common.mobileby import MobileBy
from selenium.webdriver.android.webdriver import WebDriver


class BasePage:
    def __init__(self, driver: WebDriver = None):
        self.driver = driver

    # 获取到元素且对元素进行点击操作
    def find_click(self, locator):
        self.find(locator).click()

    # 获取到元素
    def find(self, locator):
        return self.driver.find_element_by_xpath(locator)

    # 滑动屏幕，获取到指定文本元素并对其进行点击操作
    def swip_click(self, text):
        self.driver.find_element(MobileBy.ANDROID_UIAUTOMATOR,
                                 'new UiScrollable(new UiSelector().'
                                 'scrollable(true).instance(0)).'
                                 'scrollIntoView(new UiSelector().'
                                 f'text("{text}").instance(0));').click()

    # 读取yaml文件，并获取文件中的属性，通过判断属性执行对应的操作
    def parse_action(self, path):
        with open(path, 'r', encoding='utf-8') as f:
            steps: list[dict] = yaml.safe_load(f)
            for step in steps:
                if step['action'] == 'find_click':
                    self.find_click(step['locator'])
                if step['action'] == 'find':
                    self.find(step['locator'])
                if 'send' == step['action']:
                    if len(step['infoList']) > 0:
                        for info in step['infoList']:
                            if info['action'] == 'find':
                                self.find(info['locator']).send_keys(info['value'])
                            if info['action'] == 'find_click':
                                self.find_click(info['locator'])
